<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50">
    <div class="text-center px-6 py-8 bg-white shadow rounded-lg">
      <h1 class="text-lg font-semibold text-gray-800 mb-2">微信登录</h1>
      <p class="text-sm text-gray-500">{{ statusMessage }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useApi } from '~/utils/apiConfig'

const route = useRoute()
const { showSuccess, showError } = useToast()
const api = useApi('freelancer')

const statusMessage = ref('正在确认微信授权，请稍候...')

const REDIRECT_STORAGE_KEY = 'freelancer_redirect_url'
const WECHAT_STATE_STORAGE_KEY = 'freelancer_wechat_oauth_state'

const backToLogin = async () => {
  await navigateTo('/login')
}

const handleWeChatLogin = async () => {
  if (typeof window === 'undefined') {
    return
  }

  const code = typeof route.query.code === 'string' ? route.query.code : ''
  const state = typeof route.query.state === 'string' ? route.query.state : null

  if (!code) {
    showError('缺少微信授权信息，请重试登录')
    await backToLogin()
    return
  }

  const expectedState = localStorage.getItem(WECHAT_STATE_STORAGE_KEY)
  if (expectedState && state !== expectedState) {
    localStorage.removeItem(WECHAT_STATE_STORAGE_KEY)
    showError('微信登录状态校验失败，请重试')
    await backToLogin()
    return
  }

  try {
    statusMessage.value = '正在登录...'
    const response = await api.post('/login_by_weixin', {
      code,
      state,
    })

    if (response.code !== 0) {
      showError(response.message || '微信登录失败')
      await backToLogin()
      return
    }

    localStorage.setItem('userToken', response.data.token)
    localStorage.setItem('userInfo', JSON.stringify(response.data.user))
    localStorage.removeItem(WECHAT_STATE_STORAGE_KEY)

    const redirectTarget = localStorage.getItem(REDIRECT_STORAGE_KEY) || '/profile'
    localStorage.removeItem(REDIRECT_STORAGE_KEY)

    showSuccess('登录成功！')
    await navigateTo(redirectTarget)
  } catch (error) {
    console.error('微信登录失败:', error)
    showError('微信登录失败，请稍后重试')
    await backToLogin()
  }
}

onMounted(() => {
  handleWeChatLogin()
})

definePageMeta({
  alias: ['/weixinLogin'],
})
</script>
